package pheeraphonglek.dictionary.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import pheeraphonglek.dictionary.transform.Constants;
import pheeraphonglek.dictionary.transform.WordIndex;
import pheeraphonglek.dictionary.transform.model.Dictionary;
import pheeraphonglek.dictionary.transform.model.TransformDictionary;
import pheeraphonglek.dictionary.transform.model.Vocabulary;

public class Transform {

	List<String> lDictionay;

	public Transform() {
		lDictionay = new ArrayList<String>();
		lDictionay.add(Constants.DICTIONARY_HOPE);
		lDictionay.add(Constants.DICTIONARY_LONGDO);
		lDictionay.add(Constants.DICTIONARY_NECTEC1);
		lDictionay.add(Constants.DICTIONARY_NECTEC2);
		lDictionay.add(Constants.DICTIONARY_NONTRI);
		lDictionay.add(Constants.DICTIONARY_ROYAL);
		lDictionay.add(Constants.DICTIONARY_VOLBILIS);
	}
	
	public TransformDictionary findWord(String word) throws IOException{
		
		String strUrl = String.format("http://dict.longdo.com//mobile.php?search=%s", word);
		URL url = new URL(strUrl);
		URLConnection yc = url.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				yc.getInputStream(),"UTF-8"));
		String inputLine;
		StringBuilder data = new StringBuilder();

		while ((inputLine = in.readLine()) != null) {
			data.append(inputLine);
		}
		in.close();
		
		TransformDictionary tDicaionary = new TransformDictionary();
		List<Dictionary> rDicaionary = new ArrayList<Dictionary>();
		Transform trans = new Transform();
		String body = trans.getBody(data.toString());
		List<String> lDic = trans.getDictionaryList(body);
		for (String dicName : lDic) {
			Dictionary dictionary = new Dictionary();
			dictionary.setName(dicName);
			String rawDic = trans.getRawDictionary(dicName, body);
			List<Vocabulary> vocab = trans.getWords(rawDic);
			dictionary.setVocabularyList(vocab.toArray(new Vocabulary[vocab.size()]));
			rDicaionary.add(dictionary);
		}
		
		tDicaionary.setDictionary(rDicaionary.toArray(new Dictionary[rDicaionary.size()]));
		return tDicaionary;
		
	}

	// แยก tag body ออกมาจาก html ทั้งผลการค้นหา
	public String getBody(String html) {
		Integer startIndex, endIndex;
		startIndex = html.indexOf("<body>");
		endIndex = html.indexOf("</body>", startIndex);
		String result = html.substring(startIndex, endIndex + 7);
		return result;
	}

	// แยก tag table ซึ่งจะบรรจุความหมายของคำศัพท์แต่ละ dictionary ไว้
	public String getRawDictionary(String name, String body) {
		String result = new String();
		Integer startIndex, endIndex;
		startIndex = body.indexOf(name);
		startIndex = body.indexOf("<table", startIndex);
		endIndex = body.indexOf("</table>", startIndex);
		result = body.substring(startIndex, endIndex + 8);
		return result;

	}

	// แยก tag ตาม parameter พร้อมกำหนด index เริ่มต้น
	public String getRawTag(String tagName, String body, WordIndex index) {
		String result = new String();
		String startTag = String.format("<%s", tagName);
		String endTag = String.format("</%s>", tagName);
		index.startIndex = body.indexOf(startTag, index.startIndex);
		index.endIndex = body.indexOf(endTag, index.startIndex)
				+ tagName.length() + 3;
		result = body.substring(index.startIndex, index.endIndex);
		return result;
	}

	// แยก tag tr ซึ่งบรรจุ คำศัพท์และความหมายจาก tag tbody
	public List<Vocabulary> getWords(String rawDictionary) {
		WordIndex wIndex = new WordIndex();
		List<Vocabulary> lVol = new ArrayList<Vocabulary>();
		List<String> trTag = new ArrayList<String>();
		Integer wordLength = rawDictionary.length();
		String tmp = "";
		while (wIndex.endIndex < wordLength - 1) {
			try {
				tmp = getRawTag("tr", rawDictionary, wIndex);
			} catch (Exception ex) {
			}
			if (tmp.equalsIgnoreCase(""))
				break;
			trTag.add(tmp);
			tmp = "";
			wIndex.startIndex = wIndex.endIndex;
		}
		wIndex.startIndex = 0;
		wIndex.endIndex = 0;
		for (String w : trTag) {
			Vocabulary vol = new Vocabulary();
			try {
				wIndex.startIndex = 0;
				wIndex.endIndex = 0;
				tmp = getRawTag("td", w, wIndex);
			} catch (Exception ex) {
			}
			tmp = removeTag(tmp);
			vol.setVocap(tmp);

			try {
				wIndex.startIndex = wIndex.endIndex;
				tmp = getRawTag("td", w, wIndex);
			} catch (Exception ex) {
			}
			tmp = removeTag(tmp);
			vol.setMean(tmp);
			lVol.add(vol);
		}
		return lVol;
	}


	// ค้นหา Dictionary ที่ระบบเรารองรับ เพื่อใช้ในการวน loop
	// ดึงข้อมูลคำสัพท์ออกมา
	public List<String> getDictionaryList(String body) {
		List<String> lDic = new ArrayList<String>();
		for (String i : lDictionay) {
			if (body.contains(i)) {
				lDic.add(i);
			}
		}
		return lDic;

	}

	// เอา tag ทั้งหมดออก
	public String removeTag(String data) {
		String result = data;
		Integer startIndex = 0, endIndex = 0;
		while (true) {
			startIndex = result.indexOf("<", startIndex);
			if (startIndex == -1)
				break;
			endIndex = result.indexOf(">", startIndex);
			result = result.substring(0, startIndex)
					+ result.substring(endIndex + 1, result.length());
		}
		return result;
	}
}
